package cn.ly.rabbit.rabbitListener;

import cn.ly.rabbit.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听User队列
 */
@Component
@RabbitListener(queues = RabbitConfig.User_Queue_Name)  //这里监听叫myUser.queue的队列
public class UserQueueListener {


    @RabbitHandler
    public void process(@Payload String user, Channel channel, Message message)  {
        try {
            //拿到消息
//            String mm = new String(message.getBody());
            System.out.println("监听到USer_Queue的str消息：>>>>>>>>>>>>>>msg:"+user);
            //...业务逻辑
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  //第二个参数表示批量确认
        } catch (Exception e) {
            System.out.println(">>>>>>>>>>>>>>>拒绝任务");
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);   //第二个参数表示是否重新返回队列：requeue
            } catch (IOException e1) {
                System.out.println(">>>>>>>>>>>>>>>拒绝报错");
            }
        }
    }


//    @RabbitHandler
//    public void process2(@Payload User user, Channel channel, Message message)  {
//        try {
//            //拿到消息
////            String mm = new String(message.getBody());
//            System.out.println("监听到USer_Queue的user消息：>>>>>>>>>>>>>>msg:"+user.getName());
//            //...业务逻辑
//            //手动确认
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  //第二个参数表示批量确认
//        } catch (Exception e) {
//            System.out.println(">>>>>>>>>>>>>>>拒绝任务");
//            try {
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);   //第二个参数表示是否重新返回队列：requeue
//            } catch (IOException e1) {
//                System.out.println(">>>>>>>>>>>>>>>拒绝报错");
//            }
//        }
//    }
}
